import { defineStore } from 'pinia'
import { loginBySms, loginByPassword, logout, getUserInfo as fetchUserInfo, getUserInfoById } from '@/api/user'
import { setToken, getToken, removeToken, setUserInfo, getUserInfo as getStoredUserInfo, removeUserInfo } from '@/utils/auth'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken() || '',
    userInfo: getStoredUserInfo() || {},
    roles: []
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    username: (state) => state.userInfo?.username || '用户'
  },
  
  actions: {
    // 手机号验证码登录
    async loginBySms(loginData) {
      // 目前没有登陆接口 直接跳转return
      // const redirect = router.currentRoute.value.query.redirect || '/'
      // router.push(redirect)
      // return Promise.resolve({})
      // return
      try {
        const { data } = await loginBySms(loginData)
        this.token = data.token
        setToken(data.token)
        
        // 获取用户信息
        await this.getUserInfo()
        
        // 处理重定向
        const redirect = router.currentRoute.value.query.redirect || '/'
        router.push(redirect)
        
        return Promise.resolve(data)
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 手机号验证码登录
    async loginByPassword(loginData) {
      // 目前没有登陆接口 直接跳转return
      // const redirect = router.currentRoute.value.query.redirect || '/'
      // router.push(redirect)
      // return Promise.resolve({})
      // return
      try {
        const { data } = await loginByPassword(loginData)
        this.token = `${data.tokenType} ${data.accessToken}`
        setToken(this.token)
        
        // 获取用户信息
        this.userInfo = data.userInfo
        setUserInfo(data.userInfo)
        
        // 处理重定向
        const redirect = router.currentRoute.value.query.redirect || '/'
        router.push(redirect)
        
        return Promise.resolve(data)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 获取用户信息
    async getUserInfo() {
      try {
        const { data } = await fetchUserInfo()
        this.userInfo = data
        setUserInfo(data)
        return Promise.resolve(data)
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 根据用户ID获取用户信息
    async getUserInfoById(userId) {
      try {
        const { data } = await getUserInfoById(userId)
        this.userInfo = data
        setUserInfo(data)
        return Promise.resolve(data)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 退出登录
    async logout() {
      console.log('开始执行退出登录...')
      try {
        await logout()
      } catch (error) {
        console.error('登出错误', error)
      } finally {
        // 清除token和用户信息
        this.token = ''
        this.userInfo = {}
        removeToken()
        removeUserInfo()
        
        // 跳转到登录页
        router.push('/login')
      }
    },
    
    // 重置状态
    resetState() {
      this.token = ''
      this.userInfo = {}
      this.roles = []
    }
  }
}) 